<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webgl着色器</title>
  <script src="lib/webgl-debug.js"></script>
  <script src="lib/webgl-utils.js"></script>
  <script src="lib/cuon-utils.js"></script>
  <script src="lib/cuon-matrix.js"></script>
</head>

<body onload="main()">
  <canvas id="canvas" width="400" height="490"></canvas>
</body>
<script>
  // 顶点着色器伪代码
  var vShder_source = `
  attribute vec4 position;
  uniform mat4 matrix;
void main(){
gl_Position =matrix*position; //设置坐标
// gl_Position =position; //设置坐标
}
`
  //片元着色器伪代码
  var fShder_source = `
void main(){
gl_FragColor = vec4(0.5,0.0,0.0,1.0); //设置颜色
}
`
  var canvas;
  var gl;

  var tx = 0.0, ty = 0.0, tz = 0.0;
  var sx = 1.0, sy = 1.0, sz = 0.0;
  var angle = 0;
  function main() {
    init();
    draw();
  }

  function init() {
    canvas = document.getElementById('canvas');
    //  获取上下文对象
    gl = getWebGLContext(canvas);
    //  初始化着色器
    if (!initShaders(gl, vShder_source, fShder_source)) {
      return;
    }

  }

  function animation(time) {
    requestAnimationFrame(animation);
    angle=(0.5 + 0.5 * Math.sin(time/10000))*360;
    var speed = time;
    tx = 0.5 + 0.5 * Math.sin(time/10000);
    ty = 0.5 + 0.5 * Math.sin(time/10000);
    sx = 0.5 + 0.5 * Math.sin(time/10000);
    sy = 0.5 + 0.5 * Math.sin(time/10000);
    draw();
  }

  animation();

  function draw() {
    var n = initVertex(gl);
    if (n < 0) {
      console.log("无法获取顶点相关信息");
      return;
    }

    var modelMatrix = new Matrix4();
    modelMatrix.setRotate(angle, 0, 0, 1);
    modelMatrix.translate(tx, ty, tz);
    modelMatrix.scale(sx, sy, sz);

    var matrix = gl.getUniformLocation(gl.program, "matrix");
    gl.uniformMatrix4fv(matrix, false, modelMatrix.elements);

    // 指定一个覆盖canvas的颜色
    gl.clearColor(0, 0, 0, 1.0);
    // 清除指定的缓冲区
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.drawArrays(gl.TRIANGLE_FAN, 0, n);
  }



  function initVertex(gl) {
    var verties = new Float32Array([0.5, 0.5, 0.5, -0.5, -0.5, -0.5]);
    var vertexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, verties, gl.STATIC_DRAW);
    var position = gl.getAttribLocation(gl.program, "position");
    if (position < 0) {
      console.log("找不到属性position")
      return -1;
    }
    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
    gl.enableVertexAttribArray(position);
    return 3;

  }

</script>

</html>